package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.dubbo.api.mongo.UserLikeApi;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitor;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户喜欢服务接口实现类
 */
@DubboService
public class UserLikeApiImpl implements UserLikeApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private FriendApi friendApi;

    /**
     * 喜欢 或 不喜欢 记录
     *
     * @param userLike
     * @return
     */
    @Override
    public boolean save(UserLike userLike) {
        Long userId = userLike.getUserId();//当前登录用户id
        Long likeUserId = userLike.getLikeUserId();//喜欢的用户id
        Boolean isLike = userLike.getIsLike();//是否喜欢 左滑右滑
        long nowTime = System.currentTimeMillis();//时间
        //1.根据当前登录用户id 喜欢的用户id 查询记录是否存在
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));
        if (mongoTemplate.exists(query, UserLike.class)) {
            //2.存在 则更新记录
            Update update = new Update();
            update.set("isLike", isLike);//是否喜欢
            update.set("updated", nowTime);//更新时间
            mongoTemplate.updateFirst(query, update, UserLike.class);
        } else {
            //3.不存在 则保存记录
            userLike.setCreated(nowTime);
            userLike.setUpdated(nowTime);
            mongoTemplate.insert(userLike);
        }
        //4.如果isLike=true，判断对方是否喜欢登录用户
        if (isLike) {
            Query query2 = new Query();
            query2.addCriteria(Criteria.where("userId").is(likeUserId).and("likeUserId").is(userId).and("isLike").is(true));
            UserLike ul = mongoTemplate.findOne(query2, UserLike.class);
            //4.1如果喜欢 将好友关系添加好友表 return true;
            if (mongoTemplate.exists(query2, UserLike.class)) {
                friendApi.makeFriends(userId, likeUserId);
                return true;
            }
        }
        return false;
    }

    //喜欢：调用服务查询我的喜欢数量
    @Override
    public Long countByUserId(Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        return mongoTemplate.count(query, UserLike.class);
    }

    //粉丝:调用服务查询喜欢我的数量
    @Override
    public Long countByLikeUserId(Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("likeUserId").is(userId));
        return mongoTemplate.count(query, UserLike.class);
    }


    //根据当前用户id 与 好友id,删除UserLike中 粉丝-喜欢记录
    @Override
    public void deleteById(Long userId, Long friendId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("likeUserId").is(friendId).and("userId").is(userId));
        mongoTemplate.remove(query, UserLike.class);
    }

    //互相关注分页查询
    @Override
    public PageResult<RecommendUser> findPageLikeEachOther(Long userId, int page, int pagesize) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.limit(pagesize).skip((page - 1) * pagesize);
        long counts = mongoTemplate.count(query, Friend.class);
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        //查询RecommendUser
        List<RecommendUser> recommendUserList = new ArrayList<>();
        for (Friend friend : friendList) {
            Long currentUserId = friend.getUserId();//当前登录用户id
            Long friendId = friend.getFriendId();//好友id
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(currentUserId);
            recommendUser.setToUserId(friendId);
            recommendUserList.add(recommendUser);
        }
        long pages = (counts / pagesize) + (counts % pagesize > 0 ? 1 : 0);
        return new PageResult<>(counts, (long) pagesize, pages, (long) page, recommendUserList);
    }

    //我关注分页查询
    @Override
    public PageResult<RecommendUser> findPageOneSideLike(Long userId, int page, int pagesize) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.limit(pagesize).skip((page - 1) * pagesize);
        long counts = mongoTemplate.count(query, UserLike.class);
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
        //查询RecommendUser
        List<RecommendUser> recommendUserList = new ArrayList<>();
        for (UserLike userLike : userLikeList) {
            Long currentUserId = userLike.getUserId();//当前登录用户id
            Long friendId = userLike.getLikeUserId();//好友id
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(currentUserId);
            recommendUser.setToUserId(friendId);
            recommendUserList.add(recommendUser);
        }
        long pages = (counts / pagesize) + (counts % pagesize > 0 ? 1 : 0);
        return new PageResult<>(counts, (long) pagesize, pages, (long) page, recommendUserList);
    }

    //粉丝分页查询
    @Override
    public PageResult<RecommendUser> findPageFens(Long userId, int page, int pagesize) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));//粉丝查询
        query.limit(pagesize).skip((page - 1) * pagesize);
        long counts = mongoTemplate.count(query, UserLike.class);
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
        //查询RecommendUser
        List<RecommendUser> recommendUserList = new ArrayList<>();
        for (UserLike userLike : userLikeList) {
            Long currentUserId = userLike.getUserId();//当前登录用户id
            Long friendId = userLike.getLikeUserId();//好友id
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(currentUserId);
            recommendUser.setToUserId(friendId);
            recommendUserList.add(recommendUser);
        }
        long pages = (counts / pagesize) + (counts % pagesize > 0 ? 1 : 0);
        return new PageResult<>(counts, (long) pagesize, pages, (long) page, recommendUserList);
    }

    //谁看过我分页查询
    @Override
    public PageResult<RecommendUser> findPageMyVisitors(Long userId, int page, int pagesize) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));//访客查询
        query.limit(pagesize).skip((page - 1) * pagesize);
        long counts = mongoTemplate.count(query, Visitor.class);
        List<Visitor> visitorList = mongoTemplate.find(query, Visitor.class);
        //查询RecommendUser
        List<RecommendUser> recommendUserList = new ArrayList<>();
        for (Visitor visitor : visitorList) {
            Long currentUserId = visitor.getUserId();//当前登录用户id
            Long friendId = visitor.getVisitorUserId();//好友id
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(currentUserId);
            recommendUser.setToUserId(friendId);
            recommendUserList.add(recommendUser);
        }
        long pages = (counts / pagesize) + (counts % pagesize > 0 ? 1 : 0);
        return new PageResult<>(counts, (long) pagesize, pages, (long) page, recommendUserList);
    }
}
